import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';

class KlChooseticketnumbers extends StatefulWidget {
  KlChooseticketnumbers(
      {super.key, required this.numberDatas, required this.callback});
  List numberDatas;
  Function(Map) callback;
  @override
  State<KlChooseticketnumbers> createState() => _KlChooseticketnumbersState();
}

class _KlChooseticketnumbersState extends State<KlChooseticketnumbers> {
  //
  late List _numberDatas = [];
  late Map _slectedNumberMaps;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _configData();
  }

  void _configData() {
    _numberDatas = widget.numberDatas;

    _slectedNumberMaps = {
      '0': [],
      '1': [],
      '2': [],
      '3': [],
      '4': [],
      '5': [],
      '6': []
    };
    setState(() {});
  }

  void _selectedNumber(String partIndexStr, Map selectingItem) {
    int partIndex = selectingItem['partIndex'];
    int index = selectingItem['index'];

    List PartsArray = _slectedNumberMaps[partIndexStr];
    bool isExist = PartsArray.indexWhere((element) =>
            element['partIndex'] == partIndex && element['index'] == index) !=
        -1;
    if (isExist) {
      PartsArray.removeWhere((element) =>
          element['partIndex'] == partIndex && element['index'] == index);
    } else {
      switch (partIndex) {
        case 0:
          {
            //字母区选中个数不超过2个
            if (_getPartIndexCountMax(partIndex) >= 1) {
              return;
            }
          }
          break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
          {
            //数字区选中个数不超过1个
            if (_getPartIndexCountMax(partIndex) >= 1) {
              return;
            }
          }
        default:
      }
      PartsArray.add(selectingItem);
    }

    // print('_slectedNumberMaps === $_slectedNumberMaps');
    widget.callback(_slectedNumberMaps);
    setState(() {});
  }

  // 获取当前partIndex的个数
  _getPartIndexCountMax(int partIndex) {
    int count = 0;
    List partsArray = _slectedNumberMaps[partIndex.toString()];
    if (partsArray.isNotEmpty) {
      count = partsArray
          .where((element) => element['partIndex'] == partIndex)
          .length;
    }
    return count;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,
      color: Colors.red,
      child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: _numberDatas.length,
          itemBuilder: (context, partIndex) {
            Map element = _numberDatas[partIndex];
            List _numbers = element['nums'] ?? [];
            int oddIndex = partIndex % 2;
            Color bgColor =
                oddIndex == 0 ? HexColor('#e6fff0') : HexColor('#ffecf5');
            Color rightNumColor =
                oddIndex == 0 ? HexColor('#168a43') : HexColor('#d22f7d');
            return digitsView(partIndex, _numbers,
                bgColor: bgColor, rightNumColor: rightNumColor);
          }),
    );
  }

  Widget digitsView(int partIndex, List numbers,
      {Color bgColor = Colors.white, Color rightNumColor = Colors.white}) {
    List<Widget> _rowViews = [];
    for (int i = 0; i < numbers.length; i++) {
      Map element = numbers[i];
      var codeString = element['code'];
      var isRightNum = element['isRight'];
      _rowViews.add(rowItem(partIndex, i, codeString, 25.0, 80.0,
          isRight: isRightNum, bgColor: bgColor, rightNumColor: rightNumColor));
    }
    return Container(
      height: 80,
      width: numbers.length * 25.0,
      color: bgColor,
      child: Wrap(
        children: _rowViews,
      ),
    );
  }

  Widget rowItem(
      int partIndex, int index, String num, double cellW, double cellH,
      {bool isRight = false,
      Color bgColor = Colors.white,
      Color rightNumColor = Colors.white}) {
    Color _numColor = isRight ? rightNumColor : bgColor;
    Color _textColor = isRight ? Colors.white : Colors.black;

    // if (_selectedNumbers.isNotEmpty) {
    //   for (Map element in _selectedNumbers) {
    //     int oldPartIndex = element['partIndex'];
    //     int oldIndex = element['index'];
    //     if (partIndex == oldPartIndex && index == oldIndex) {
    //       _numColor = rightNumColor;
    //       _textColor = Colors.white;
    //     }
    //   }
    // }

    if (_slectedNumberMaps.isNotEmpty) {
      List partsArray = _slectedNumberMaps[partIndex.toString()];
      if (partsArray.isNotEmpty) {
        for (Map element in partsArray) {
          int oldPartIndex = element['partIndex'];
          int oldIndex = element['index'];
          if (partIndex == oldPartIndex && index == oldIndex) {
            _numColor = rightNumColor;
            _textColor = Colors.white;
          }
        }
      }
    }

    return GestureDetector(
        onTap: () {
          print('partIndex:$partIndex index:$index num:$num');
          var selectedItem = {
            'partIndex': partIndex,
            'index': index,
            'num': num
          };
          _selectedNumber(partIndex.toString(), selectedItem);
        },
        child: Container(
          height: cellH,
          width: cellW,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: bgColor,
            border: Border(
              bottom: BorderSide(color: HexColor('#dddddd'), width: 1),
              right: BorderSide(color: HexColor('#dddddd'), width: 1),
            ),
          ),
          child: Container(
            width: 20,
            height: 20,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: _numColor,
              borderRadius: const BorderRadius.all(Radius.circular(20 * 0.5)),
            ),
            child: Text(
              num,
              style: TextStyle(
                fontWeight: FontWeight.w600,
                fontSize: 12,
                color: _textColor,
              ),
            ),
          ),
        ));
  }
}
